<?php
namespace backend\controllers;

use Yii;
use common\models\AuthItem;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\AuthItemForm;
use common\models\AuthItemChild;

/**
 * AuthItemController implements the CRUD actions for AuthItem model.
 */
class AuthItemController extends Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => [
                        'POST'
                    ]
                ]
            ]
        ];
    }

    /**
     * Lists all AuthItem models.
     * 
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => AuthItem::find()
        ]);
        return $this->render('index', [
            'dataProvider' => $dataProvider
        ]);
    }

    /**
     * Displays a single AuthItem model.
     * 
     * @param string $id            
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id)
        ]);
    }

    /**
     * Creates a new AuthItem model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * 
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new AuthItemForm();
        $model->isNewRecord = true;
        $post = Yii::$app->request->post();
        if ($post) {
            $model->load($post);
            if ($model->type == 1) {
                $status = $model->createRole($model->name, $model->description);
                if ($status && ! empty($post['AuthItemForm']['child'])) {
                    $this->roleAssign($model->name, $post['AuthItemForm']['child']);
                }
            } else {
                $status = $model->createPermission($model->name, $model->description);
            }
            return $this->redirect('create');
        }
        return $this->render('create', [
            'model' => $model,
            'data' => AuthItem::find()->where([
                'type' => 2
            ])
                ->all()
        ]);
    }

    /**
     * Updates an existing AuthItem model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * 
     * @param string $id            
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $data = [];
        if ($model->type == 1) {
            $data = AuthItem::find()->where([
                'type' => 2
            ])->all();
            $model->child = array_column(AuthItemChild::find()->where([
                'parent' => $model->name
            ])
                ->asArray()
                ->all(), 'child');
        }
        $post = Yii::$app->request->post();
        if ($model->load($post) && $model->save()) {
            if ($model->type == 1 && ! empty($post['AuthItem']['child'])) {
                $this->roleAssign($model->name, $post['AuthItem']['child']);
            }
            return $this->redirect([
                'view',
                'id' => $model->name
            ]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'data' => $data
            ]);
        }
    }

    /**
     * Deletes an existing AuthItem model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * 
     * @param string $id            
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        
        return $this->redirect([
            'index'
        ]);
    }

    /**
     * Finds the AuthItem model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * 
     * @param string $id            
     * @return AuthItem the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AuthItem::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function roleAssign($name, $child)
    {
        $model = new AuthItemChild();
        $row = [];
        $model->parent = $name;
        foreach ($child as $val) {
            $model->child = $val;
            if ($model->validate()) {
                $row[] = [
                    'parent' => $name,
                    'child' => $val
                ];
            }
        }
        $model->deleteAll('parent=:parent', [
            'parent' => $name
        ]);
        \Yii::$app->db->createCommand()
            ->batchInsert('auth_item_child', [
            'parent',
            'child'
        ], $row)
            ->execute();
    }
}
